﻿using StarsAdmin.Core.Extensions;
using System.Security.Cryptography;
using System.Text;

namespace StarsAdmin.Core.Helpers
{
    public class MD5Helper
    {
        /// <summary>
        /// 16位MD5加密
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string MD5Encrypt16(string password)
        {
            if (password.IsNullOrWhiteSpace())
                return string.Empty;

            using var md5 = MD5.Create();
            byte[] bytes = md5.ComputeHash(Encoding.Default.GetBytes(password));
            string t2 = BitConverter.ToString(bytes, 4, 8);
            t2 = t2.Replace("-", string.Empty);
            return t2;
        }

        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string MD5Encrypt32(string password = "")
        {
            if (password.IsNullOrWhiteSpace())
                return string.Empty;

            string pwd = string.Empty;
            //实例化一个md5对像
            using MD5 md5 = MD5.Create();
            // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
            // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得
            foreach (var item in s)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符
                pwd = string.Concat(pwd, item.ToString("X2"));
            }
            return pwd;
        }

        /// <summary>
        /// 64位MD5加密
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string MD5Encrypt64(string password)
        {
            if (password.IsNullOrWhiteSpace())
                return string.Empty;

            // 实例化一个md5对像
            // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
            using MD5 md5 = MD5.Create();
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
            return Convert.ToBase64String(s);
        }

        /// <summary>
        /// 获得哈希值
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static string GetHash(Stream stream)
        {
            StringBuilder sb = new();
            using var md5 = MD5.Create();
            byte[] hashBytes = md5.ComputeHash(stream);
            foreach (byte bt in hashBytes)
            {
                sb.Append(bt.ToString("x2"));
            }
            return sb.ToString();
        }
    }
}